package com.cardbaobao.cardbabyclient.ui.fragment.collect;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.CreditDetailActivity;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.ui.activity.SpeedCardActivity;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.fragment.base.BaseFragment;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.widget.refresh.FooterLoadMore;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 2017/7/5 18:46.
 */

public class CollectCreditFragment extends BaseFragment {

    private String prePageId;

    public void setBuriedInfo(String prePageId){
        this.prePageId=prePageId;
    }

    private static final int PAGE_START=1;
    private int page=PAGE_START;
    private boolean isLoading;
    @BindView(R.id.srLayout)
    SmartRefreshLayout srLayout;
    @BindView(R.id.footerLoadMore)
    FooterLoadMore footerLoadMore;
    @BindView(R.id.recycler_view)
    RecyclerView recyclerView;
    private CreditAdapter adapter;

    private boolean canLoadMore=true;

    private List<CreditBean> data=new ArrayList<>();
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_my_collect;
    }

    @Override
    protected void initViewFinish(View view, Bundle savedInstanceState) {

        mCurrentPageId= Self.Page.app_collected_credit_card_page;

        footerLoadMore.setStateNoMoreDataStr("没有更多数据了");
        srLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                page++;
                loadData();
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                page=PAGE_START;
                loadData();
            }
        });

        recyclerView.setLayoutManager(new LinearLayoutManager(mContext));

        adapter=new CreditAdapter();

        loadData();
    }

    private class CreditBean{
        /**
         * SeriesCard :
         * withdrawalLimit : 50.0%取现额
         * id : 11584
         * title : 中信魔力摩尔联名卡 金卡1（银联）
         * applyNum : 0人申请
         * Feature : 女性健康专属保险
         最高5倍积分奖励
         专享全年6次免费高端SAP服务
         * logoUrl : /uploadFiles/uploadImgs/productcreditcard/20151091515538808.jpg
         * cardLimit : 10-50万额度
         * tags : ["优惠折扣日","酒店车辆接送"]
         */
        private int id;
        private String title;
        private String applyNum;
        private String Feature;
        private String logoUrl;



        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getTitle() {
            return title;
        }

        public void setTitle(String title) {
            this.title = title;
        }

        public String getApplyNum() {
            final String reg="[^0-9]";
            final Pattern pattern = Pattern.compile(reg);
            final Matcher matcher=pattern.matcher(this.applyNum);
            return matcher.replaceAll("").trim();
        }

        public void setApplyNum(String applyNum) {
            this.applyNum = applyNum;
        }

        public String getFeature() {
            return Feature;
        }

        public void setFeature(String Feature) {
            this.Feature = Feature;
        }

        public String getLogoUrl() {
            return logoUrl;
        }

        public void setLogoUrl(String logoUrl) {
            this.logoUrl = logoUrl;
        }
    }

    private void loadData(){
        if(isLoading){
            return;
        }
        showProgressDialog(false);
        isLoading=true;
        Observable<String> observable=
                Api.collectedCreditCard("ZCC0101",
                        String.valueOf(mApplication.getUser().getID()),
                        String.valueOf(page),
                        String.valueOf(Constant.SIZE));
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {
                isLoading=false;
                dismissProgressDialog();
                if(recyclerView.getAdapter()==null){
                    recyclerView.setAdapter(adapter);
                }
                srLayout.finishRefresh();
                srLayout.finishLoadmore();
                if(canLoadMore){
                    footerLoadMore.setStatePreLoading();
                    srLayout.setLoadmoreFinished(false);
                }else{
                    footerLoadMore.setStateNoMoreData();
                    srLayout.setLoadmoreFinished(true);
                }
            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                page--;
                if(page<PAGE_START){
                    page=PAGE_START;
                }
                if(recyclerView.getAdapter()==null){
                    recyclerView.setAdapter(adapter);
                }
            }

            @Override
            public void onNext(String s) {
                JSONObject json= JSON.parseObject(s);
                if(json!=null){
                    if(json.getIntValue("code")==1){
                        List<CreditBean> temp=null;
                        JSONArray array=json.getJSONArray("data");
                        if(array!=null){
                            if(array.size()>0){
                                temp=new ArrayList<>();
                                JSONObject object;
                                CreditBean bean;
                                for(int i=0,size=array.size();i<size;i++){
                                    object=array.getJSONObject(i);
                                    bean=new CreditBean();
                                    bean.setApplyNum(object.getString("applyNum"));
                                    bean.setTitle(object.getString("title"));
                                    bean.setId(object.getIntValue("id"));
                                    bean.setLogoUrl(object.getString("logoUrl"));
                                    bean.setFeature(object.getString("Feature"));
                                    temp.add(bean);
                                }
                                canLoadMore=true;
                            }else{
                                canLoadMore=false;
                            }
                        }
                        if(temp!=null){
                            if(page==PAGE_START){
                                data.clear();
                            }
                            if(temp.size()>0){
                                data.addAll(temp);
                            }
                            adapter.notifyDataSetChanged();
                        }
                    }else{
                        ToastUtil.showToast(json.getString("result"));
                    }
                }
            }
        });
    }

    private class ContentHolder extends RecyclerView.ViewHolder{
        private TextView tvTitle;
        private TextView tvDes;
        private TextView tvApplyCount;
        private ImageView pic;
        private ContentHolder(View itemView){
            super(itemView);
            tvTitle= (TextView) itemView.findViewById(R.id.tv_title);
            tvDes= (TextView) itemView.findViewById(R.id.tv_description);
            tvApplyCount= (TextView) itemView.findViewById(R.id.tv_apply_count);
            pic= (ImageView) itemView.findViewById(R.id.iv_pic);
        }
    }

    private class NoDataHolder extends RecyclerView.ViewHolder{
        private TextView tvView;
        private NoDataHolder(View itemView){
            super(itemView);
            tvView= (TextView) itemView.findViewById(R.id.tv_view);
        }
    }

    private class CreditAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
        private int margin32;
        private int margin26;
        private int radian;
        private CreditAdapter(){
            this.margin32 = DensityUtil.dp2px(16);
            this.margin26=DensityUtil.dp2px(13);
            this.radian=DensityUtil.dp2px(6);
        }
        private static final int TYPE_CONTENT=1;
        private static final int TYPE_NO_DATA=2;
        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater=LayoutInflater.from(parent.getContext());
            if(viewType==TYPE_CONTENT){
                View itemView= inflater.inflate(R.layout.item_collect_credit,parent,false);
                return new ContentHolder(itemView);
            }
            if(viewType==TYPE_NO_DATA){
                View itemView=inflater.inflate(R.layout.item_collect_no_data,parent,false);
                return new NoDataHolder(itemView);
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
            if(holder instanceof ContentHolder){
                RecyclerView.MarginLayoutParams layoutParams=
                        (RecyclerView.MarginLayoutParams) holder.itemView.getLayoutParams();
                layoutParams.topMargin=margin32;
                layoutParams.leftMargin=margin26;
                layoutParams.rightMargin=margin26;
                ContentHolder contentHolder= (ContentHolder) holder;
                final CreditBean bean=data.get(position);
                contentHolder.tvTitle.setText(bean.getTitle());
                contentHolder.tvApplyCount.setText(bean.getApplyNum());
                contentHolder.tvDes.setText(bean.getFeature());
                ImageLoaderUtil.displayImageWithPlaceHolder(URLUtil.CBB_IMG_URL+bean.logoUrl,
                        contentHolder.pic,
                        R.mipmap.img_default_rectangle,
                        radian);
                contentHolder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SelfUtils.buriedClickData(Self.Action.app_click_mine_collect_credit_card_item,
                                Self.Action.app_click_mine_collect_credit_card_item_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        Intent intent=new Intent(mContext, CreditDetailActivity.class);
                        intent.putExtra(CreditDetailActivity.CARD_ID_S,
                                String.valueOf(bean.getId()));
                        intent.putExtra(CreditDetailActivity.CARD_NAME_S,
                                bean.getTitle());
                        intent.putExtra(BaseActivity.PRE_PAGE_ID_S,
                                mCurrentPageId);
                        startActivity(intent);
                    }
                });
            }
            if(holder instanceof NoDataHolder){
                ((NoDataHolder) holder).tvView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        SelfUtils.buriedClickData(Self.Action.app_click_mine_collect_credit_card_view_other,
                                Self.Action.app_click_mine_collect_credit_card_view_other_des,
                                mEnterPageTime,
                                mCurrentPageId,
                                prePageId);
                        initIntent();
                            //跳急速办卡
                        mIntent.setClass(mContext,SpeedCardActivity.class);
                        mIntent.putExtra(BaseActivity.PRE_PAGE_ID_S,mCurrentPageId);
                        startActivity(mIntent);
                        getActivity().finish();
                    }
                });
            }
        }

        @Override
        public int getItemViewType(int position) {
            return data.size()==0?TYPE_NO_DATA:TYPE_CONTENT;
        }

        @Override
        public int getItemCount() {
            return data.size()==0?1:data.size();
        }
    }
}
